package com.gp.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

public class CuratorDemo {

    private static String CONNECTION_STR = "119.23.20.185:2181,119.23.20.185:2182,119.23.20.185:2183";

    public static void main(String[] args) {

        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                    .connectString(CONNECTION_STR).sessionTimeoutMs(5000)
                                // 衰减重试
                    .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();

        curatorFramework.start();

//        createData(curatorFramework);
//        updateData(curatorFramework);
        deleteData(curatorFramework);
    }

    private static void createData(CuratorFramework curatorFramework){
        try {
            curatorFramework.create().creatingParentsIfNeeded()
//                    .withMode(CreateMode.EPHEMERAL) // 创建临时节点
                    .withMode(CreateMode.PERSISTENT) // 创建临时节点
                    .forPath("/data/program","test".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void updateData(CuratorFramework curatorFramework){
        try {
            curatorFramework.setData().forPath("/data/program","up".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void deleteData(CuratorFramework curatorFramework){
        try {
            curatorFramework.delete().forPath("/data/program");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
